/* Hawk - An OSGI Based Test Framework
 *
 * Copyright (C) 2010 http://code.google.com/p/hawk-framework/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
package org.hawk.core.util;

import java.io.IOException;
import java.io.StringReader;

import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * This is a utility class used to help in DOM processing
 * 
 * @author Rodrigo Prestes Machado
 * @version November 16, 2009
 */
public class DOMUtil
{
	/**
	 * This method is used to returns the node value
	 * 
	 * @param A XML node
	 * @return The node value in string format
	 */
	public static String getNodeValue(Node node)
	{
		String nodeValue = null;
		if (node.hasChildNodes())
		{
			NodeList nodeList = node.getChildNodes();
			for (int i=0; i < nodeList.getLength(); i++)
			{
				Node nodeChild = nodeList.item(i);
				if (nodeChild.getNodeType() == 3)
				{
					nodeValue = nodeChild.getNodeValue();
				}
			}
		}
		return nodeValue;
	}
	
	/**
	 * This method is used to create a document using string content
     *
	 * @param A XML file string format
	 * @return A DOM document
	 */
	public static Document createDocument(String content)
	{
		Document doc = null;
		StringReader stringReader = new StringReader(content);
		InputSource inputSource = new InputSource(stringReader);
		
		DOMParser parser = new DOMParser();
		try {
			parser.parse(inputSource);
			doc = parser.getDocument();
		}
		catch (SAXException e){
			e.printStackTrace();
			return null;
		}
		catch (IOException e){
			e.printStackTrace();
			return null;
		}
		return doc;
	}
	
	
}